package com.example.Demo_DelayQueue;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayTask implements Delayed {
    public String name;
    public Long delayTime;
    public TimeUnit delayTimeUnit;
    public Long executeTime;//ms

    public DelayTask(String name, long delayTime, TimeUnit delayTimeUnit) {
        this.name = name;
        this.delayTime = delayTime;
        this.delayTimeUnit = delayTimeUnit;
        this.executeTime = System.currentTimeMillis() + delayTimeUnit.toMillis(delayTime);
    }

    //getDelay方法的作用即是计算当前时间到执行时间之间还有多长时间。
    //如下，返回unit单位下该延迟时间的值。
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(executeTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    //compareTo方法的作用即是判断队列中元素的顺序谁前谁后。
    //当前元素比队列元素后执行时，返回一个正数，比队列元素先执行时返回一个负数，否则返回0.
    //就是将该元素进行排队时,插队到最前还是排队到最后
    @Override
    public int compareTo(Delayed o) {
        if(this.getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) {
            return 1;
        }else if(this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) {
            return -1;
        }
        return 0;
    }
    public void sayHello(){
        System.out.println(name+"hellow");

    }

    @Override
    public String toString() {
        return  name;
    }
}